package com.etrans.web.gps.business.report.controller;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.report.domain.AbnomalVeVO;
import com.etrans.web.gps.business.report.service.AbnomalVehicleService;
import com.etrans.web.gps.business.system.service.CommonService;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.util.grid.FlexiGridUtil;

/**
 * 问题车辆筛查Controller
 * @author zhangw
 *
 */
@Controller
@RequestMapping("/report/abnomalVe/*")
public class AbnomalVehicleController extends BaseController{
	
private final static Logger logger = LoggerFactory.getLogger(AbnomalVehicleController.class);
	
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private AbnomalVehicleService abnomalService;
	
	/**
	 * 页面跳转入口
	 * @return
	 */
	@RequestMapping(value="getAbnomalVehicle.html")
	public String getAlarmSynAnalysis(Model model){
		return "views/business/report/abnomalVehicle";
	}
	
	/**
	 * 根据查询条件查询
	 * @return  登录用户权限下的全部业户的问题车辆数量以展示柱状图
	 */
	@ResponseBody
	@RequestMapping(value = "queryAbnomalVeBarChart.html")
	public Map<String,Object> queryAbnomalVeBarChart(){
		Map<String,Object> resultMap =new HashMap<String, Object>();
		try {
			//查询该权限下的区域
			int areaId= this.getSysUser().getArea_id();
			//获取查询条件
			Map<String,Object> params = getReqParameters();
			String timeType = params.get("timeType") == null? "" : String.valueOf(params.get("timeType"));
			String dateTime = params.get("dateTime") == null? "" : String.valueOf(params.get("dateTime"));
			String queryType = params.get("queryType") == null? "" : String.valueOf(params.get("queryType"));
			String queryContent = params.get("queryContent") == null? "" : String.valueOf(params.get("queryContent"));
			//判断查询类型分别查询
			resultMap = abnomalService.queryBarChartByEnt(timeType, dateTime,queryType, queryContent, areaId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
        return resultMap;
	}
	
	
	/**
	 * 根据业户名和查询时间查询
	 * @return  登录用户权限下的全部业户的问题车辆
	 */
	@ResponseBody
	@RequestMapping(value = "getAbnomalVeTable.html")
	public PageVo getAbnomalVeTable(String paramsGrid){
		PageVo pageVo = new PageVo();
		try {
			//查询该权限下的区域
			int areaId = this.getSysUser().getArea_id();
			//获取查询条件
			Map<String, Object> params = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
			int size = params.get("pageSize")==null?10:Integer.parseInt(params.get("pageSize")+"");
			int page = params.get("page")==null?10:Integer.parseInt(params.get("page")+"");
			//获取查询条件
			String timeType = params.get("timeType") == null? "" : String.valueOf(params.get("timeType"));
			String dateTime = params.get("dateTime") == null? "" : String.valueOf(params.get("dateTime"));
			String queryType = params.get("queryType") == null? "" : String.valueOf(params.get("queryType"));
			String queryContent = params.get("queryContent") == null? "" : String.valueOf(params.get("queryContent"));
			List<AbnomalVeVO> result =
					abnomalService.getTableData(timeType, dateTime,queryType, queryContent, areaId, (page-1)*size, size);
			int total = abnomalService.getTableDataCount(timeType, dateTime,queryType, queryContent, areaId);
			//获取车辆颜色Map
			Map<Integer, String> colorMap = new HashMap<>();
			List<HashMap<String, Object>> colorList = commonService.queryVehicleColorList(null);
			for (HashMap<String, Object> hashMap : colorList) {
				colorMap.put(Integer.valueOf(hashMap.get("id")+""), hashMap.get("name")+"");
			}
			if (result != null && result.size() > 0) {
				for (int i = 0; i < result.size(); i++) {
					AbnomalVeVO ab = result.get(i);
					ab.setVehicleId(i + 1);
					ab.setVehicle_color_name(colorMap.get(ab.getVehicle_color()));
				}
			}
			pageVo.setTotal(total);
			pageVo.setRows(result);
			pageVo.setPage(page);
	        
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return pageVo;
	}

	/**
	 *
	 *@description  导出查询结果
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "exportQueryResult.html")
	public void exportQueryResult( HttpServletRequest request, HttpServletResponse response, String timeType, String dateTime,
			String queryType, String queryContent, String title, String StartSize, String PageSize,
			String colModel,String imgsrc) {
		try {
			//获取参数
			DecimalFormat df = new DecimalFormat("0.00");
			List<String> colModelList = JSON.parseObject(colModel, List.class);
			List<String> imgsrcList   = JSON.parseObject(imgsrc, List.class);
			int from = Integer.parseInt(StartSize);
			int size = Integer.parseInt(PageSize);
			//传入条件从MongoDB中查询出数据
			//查询该权限下的所有区域名称
			int areaId= this.getSysUser().getArea_id();
			List<AbnomalVeVO> result = abnomalService.getTableData(timeType, dateTime,queryType, queryContent, areaId, from, size);
			//获取车辆颜色Map
			Map<Integer, String> colorMap = new HashMap<>();
			List<HashMap<String, Object>> colorList = commonService.queryVehicleColorList(null);
			for (HashMap<String, Object> hashMap : colorList) {
				colorMap.put(Integer.valueOf(hashMap.get("id")+""), hashMap.get("name")+"");
			}
			if (result != null && result.size() > 0) {
				for (int i = 0; i < result.size(); i++) {
					AbnomalVeVO ab = result.get(i);
					ab.setVehicleId(i + 1);
					ab.setVehicle_color_name(colorMap.get(ab.getVehicle_color()));
				}
			}
			List<HashMap<String, Object>> rows = new ArrayList<HashMap<String, Object>>();
			for(int i = 0; i < result.size(); i++){
				HashMap<String, Object> map = new HashMap<String, Object>();
				AbnomalVeVO abVe= result.get(i);
				map.put("vehicleId", abVe.getVehicleId() == null ? "" : abVe.getVehicleId());
				map.put("vehicle_no", abVe.getVehicle_no()== null ? "" : abVe.getVehicle_no());
				map.put("vehicle_color_name",  abVe.getVehicle_color_name()==null ? "" : abVe.getVehicle_color_name());
				map.put("enterprise_name", abVe.getEnterprise_name() == null ? "" : abVe.getEnterprise_name());
				map.put("notrack_day_count", abVe.getNotrack_day_count() != null && abVe.getNotrack_day_count() >= 10 ? abVe.getNotrack_day_count(): "-") ;
				map.put("track_complete_rate", abVe.getTrack_complete_rate() != null && abVe.getTrack_complete_rate() < 85 ? df.format(abVe.getTrack_complete_rate()) : "-");
				String str = "-";
				if (abVe.getException_track_count()!= null && abVe.getTrack_normal() != null) {
					double rate = 1.0*(abVe.getTrack_normal()) / (abVe.getException_track_count() + abVe.getTrack_normal());
					str = rate < 0.95 ? df.format(rate*100) : "-";
				}
				map.put("data_correct_rate", str);
				map.put("location_exception_count", abVe.getLocation_exception_count() != null && abVe.getLocation_exception_count() >6 ? abVe.getLocation_exception_count() : "-");
				map.put("overspeed_100_count", abVe.getOverspeed_100_count() != null && abVe.getOverspeed_100_count() > 0 ? abVe.getOverspeed_100_count() : "-");
				map.put("overspeed_order", abVe.getOverspeed_order() != null && Integer.valueOf(abVe.getOverspeed_order()) > 0 ? abVe.getOverspeed_order() : "-");
				map.put("tired_duration", abVe.getTired_duration() != null && abVe.getTired_duration() > 0 ? df.format(1.00*abVe.getTired_duration()/60) : "-");
				rows.add(map);
			}
			int index = -1;
			List rowsList = new ArrayList<>();
			rowsList.add(rows);
			exportExl(request, response,title, removeHeadName(colModelList,index,-1),rowsList,imgsrcList);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}
}
